package logic

import (
	"context"
	"fmt"
	"vipshop/model/mysql"
	"vipshop/model/redisinit"
	"vipshop/pkg"
	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAddLogic) UserAdd(in *vipshoprpc.UserAddRequest) (*vipshoprpc.UserAddResponse, error) {
	// todo: add your logic here and delete this line
	capGet := redisinit.Rdb.Get("captchaAdd" + in.Phone)
	if capGet.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	sendGet := redisinit.Rdb.Get("sendSmsAdd" + in.Phone)
	if sendGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("该用户已注册")
	}
	m := mysql.User{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	err := mysql.DB.Debug().Create(&m).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	redisinit.Rdb.Del("captchaAdd" + in.Phone)
	redisinit.Rdb.Del("sendSmsAdd" + in.Phone)
	return &vipshoprpc.UserAddResponse{
		Id: int64(m.ID),
	}, nil
}
